package at.fhooe.im440.core;

import java.util.ArrayList;
import java.util.List;
import at.fhooe.im440.clock.Timer;
import at.fhooe.im440.pandora.events.EventManager;
import at.fhooe.im440.pandora.graphicsConfig.GraphicsConfig;
import at.fhooe.im440.pandora.graphicsConfig.GraphicsSystem;
import at.fhooe.im440.pandora.io.KeyboardManager;
import at.fhooe.im440.pandora.logic.entities.Clock;
import at.fhooe.im440.pandora.logic.entities.Entity;
import at.fhooe.im440.pandora.logic.entities.EntityManager;
import at.fhooe.im440.pandora.logic.entities.Ship;
import at.fhooe.im440.views.ClockView;
import at.fhooe.im440.views.GamePlayView;
import at.fhooe.im440.views.View;

public class Core {

	public KeyboardManager keyboardMgr;
	public GraphicsSystem graphicsSystem;
	public List<EntityManager> entityMgrs;
	public EventManager eventMgr;
	public at.fhooe.im440.clock.Clock clock;

	private boolean runLoop;
	
	public Core(GraphicsConfig gc){
		runLoop = false;
		this.keyboardMgr = new KeyboardManager(this);
		this.eventMgr = new EventManager(this);
		this.entityMgrs = new ArrayList<EntityManager>();
		this.graphicsSystem = new GraphicsSystem(this);
		this.setGraphicsConfiguration(gc);
		
		this.clock = new at.fhooe.im440.clock.Clock(this);
		
		Timer gameClock = new Clock("gamePlay", this, 100, 100, 200);
		
		this.clock.addTimer(gameClock);
		
		Entity rect = new Ship("rect", 0, 0, 80, 80, this);

		
		//create the views
		View gameView = new GamePlayView(this);

		gameView.getEntityMgr().addEntity(rect);
		gameView.getEntityMgr().registerEntityForKeyInput(rect);
		
		
		View clockView = new ClockView(this);

		clockView.getEntityMgr().addEntity((Entity)gameClock);
	}

	private void setGraphicsConfiguration(GraphicsConfig gc) {
		graphicsSystem.setFrameRate(gc.getFps());
		graphicsSystem.open(gc.getWidth(), gc.getWidth(), gc.isFullscreen());
	}
	
	public void addEntity(Entity e){
		//entityMgr.addEntity(e);
	}

	public void requestUpdate() {
		graphicsSystem.render();
	}
	
	public void closeWindow(){
		graphicsSystem.close();
	}
	
	public void runLoop(){
		runLoop = true;
		
		while (runLoop){
			eventMgr.handleEvents();
			requestUpdate();
		}
		
		closeWindow();
		System.exit(0);
	}
}
